package com.bc004346.travelus.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bc004346.travelus.FlightPagerActivity;
import com.bc004346.travelus.R;
import com.bc004346.travelus.adapter.FlightAdapter;
import com.bc004346.travelus.model.domain.Flight;
import com.bc004346.travelus.model.domain.Reservation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.bc004346.travelus.fragment.FlightDetailsFragment.EXTRA_FLIGHTS;
import static com.bc004346.travelus.fragment.FlightDetailsFragment.EXTRA_FLIGHT_ID;
import static com.bc004346.travelus.utility.Utility.log;

/**
 * Created by Renats on 9/4/2014.
 * The new flight list
 */
public class FlightListFragment extends ListFragment {

    //<editor-fold desc="Members">
    protected SwipeRefreshLayout mSwipeRefresh;
    private ArrayList<Flight> mFlights = new ArrayList<Flight>();
    private static final String KEY_FLIGHT = "com.bc004346.travelus.FlightListFragment.Flight";
    //</editor-fold>

    //<editor-fold desc="Overrides">
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        if (savedInstanceState != null)
            //noinspection unchecked
            mFlights = (ArrayList<Flight>) savedInstanceState.getSerializable(KEY_FLIGHT);
        FlightAdapter adapter = new FlightAdapter(getActivity(), mFlights);
        setListAdapter(adapter);

        mSwipeRefresh = (SwipeRefreshLayout) getActivity().findViewById(R.id.activity_fragment_swipeRefresh);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        try {
            outState.putSerializable(KEY_FLIGHT, mFlights);
        } catch (Exception e) {
            log(e, getActivity());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.item_selector, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        try {
            getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView absListView, int i) {
                }

                @Override
                public void onScroll(AbsListView absListView,
                                     int firstVisibleItem,
                                     int visibleItemCount,
                                     int totalItemCount) {
                    if (mSwipeRefresh != null) {
                        if (firstVisibleItem == 0) mSwipeRefresh.setEnabled(true);
                        else mSwipeRefresh.setEnabled(false);
                    }
                }
            });
        } catch (Exception e) {
            log(e, getActivity());
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        try {
            if (v.getClass() == TextView.class) {
                Toast.makeText(getActivity(),
                        String.format("You do no have any flights within the number of days specified in settings"),
                        Toast.LENGTH_LONG).show();
                return;
            }
            Intent i = new Intent(getActivity(), FlightPagerActivity.class);
            i.putExtra(EXTRA_FLIGHT_ID, position);
            i.putExtra(EXTRA_FLIGHTS, mFlights);
            startActivityForResult(i, 0);
        } catch (Exception e) {
            log(e, getActivity());
        }
    }

    //</editor-fold>

    //<editor-fold desc="Private Methods">
    public void refreshReservations(List<Reservation> reservations) {

        try {
            mFlights.clear();
            final ListView lv;
            lv = getListView();
            if (reservations.size() > 0) {
                for (Reservation res : reservations)
                    for (Flight flight : res.getFlights())
                        mFlights.add(flight);

                Collections.sort(mFlights);

                FlightAdapter adapter = new FlightAdapter(getActivity(), mFlights);
                setListAdapter(adapter);

                if (lv != null) {
                    lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                    lv.setSelector(android.R.color.darker_gray);
                }

            } else {
                ArrayAdapter<String> flightArrayAdapter = new ArrayAdapter<String>(getActivity(),
                        R.layout.list_flight_simple, new ArrayList<String>() {{
                    add(getActivity().getString(R.string.common_no_flights_found));
                }}
                );
                setListAdapter(flightArrayAdapter);
                if (lv != null)
                    lv.setChoiceMode(ListView.CHOICE_MODE_NONE);

            }
        } catch (IllegalStateException e) {
            log(e.getMessage());
        } catch (Exception e) {
            log(e, getActivity());
        }
    }

    public void refreshFlights(List<Flight> flights) {

        try {
            mFlights.clear();
            final ListView lv = getListView();
            mFlights.addAll(flights);
            if (flights.size() > 0) {

                Collections.sort(mFlights);

                FlightAdapter adapter = new FlightAdapter(getActivity(), mFlights);
                setListAdapter(adapter);

                if (lv != null) {
                    lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                    lv.setSelector(android.R.color.darker_gray);
                }

            } else {
                ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                        R.layout.list_flight_simple, new ArrayList<String>() {{
                    add(getActivity().getString(R.string.common_no_flights_found));
                }}
                );
                setListAdapter(adapter);
                if (lv != null)
                    lv.setChoiceMode(ListView.CHOICE_MODE_NONE);

            }
        } catch (Exception e) {
            log(e, getActivity());
        }
    }

    //</editor-fold>

}
